package com.automotive.can1939.service;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;

import androidx.core.app.NotificationCompat;

import com.automotive.can1939.R;
import com.automotive.can1939.can.CanManager;
import com.automotive.can1939.model.CanFrame;
import com.automotive.can1939.model.J1939Frame;
import com.automotive.can1939.ui.MainActivity;

import java.util.ArrayList;
import java.util.List;

import timber.log.Timber;

/**
 * CAN通信后台服务
 * 提供持续的CAN数据监控和处理
 */
public class CanCommunicationService extends Service implements 
        CanManager.CanDataListener, CanManager.CanStatusListener {
    
    private static final String TAG = "CanCommunicationService";
    private static final int NOTIFICATION_ID = 1001;
    private static final String CHANNEL_ID = "can_service_channel";
    
    private CanManager canManager;
    private NotificationManager notificationManager;
    private final IBinder binder = new CanServiceBinder();
    
    // 服务状态
    private boolean isServiceRunning = false;
    private int receivedFrameCount = 0;
    private int sentFrameCount = 0;
    
    // 数据统计
    private long lastFrameTime = 0;
    private List<ServiceListener> serviceListeners = new ArrayList<>();
    
    /**
     * 服务绑定器
     */
    public class CanServiceBinder extends Binder {
        public CanCommunicationService getService() {
            return CanCommunicationService.this;
        }
    }
    
    /**
     * 服务监听器接口
     */
    public interface ServiceListener {
        void onServiceStatusChanged(boolean isRunning);
        void onDataStatisticsUpdated(int receivedCount, int sentCount);
    }
    
    @Override
    public void onCreate() {
        super.onCreate();
        
        Timber.d("CAN通信服务创建");
        
        // 初始化通知管理器
        notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        createNotificationChannel();
        
        // 初始化CAN管理器
        canManager = CanManager.getInstance(this);
        canManager.addDataListener(this);
        canManager.addStatusListener(this);
    }
    
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Timber.d("CAN通信服务启动");
        
        if (!isServiceRunning) {
            startForegroundService();
            isServiceRunning = true;
            notifyServiceListeners();
        }
        
        return START_STICKY; // 服务被杀死后自动重启
    }
    
    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }
    
    @Override
    public void onDestroy() {
        super.onDestroy();
        
        Timber.d("CAN通信服务销毁");
        
        isServiceRunning = false;
        
        if (canManager != null) {
            canManager.removeDataListener(this);
            canManager.removeStatusListener(this);
            canManager.disconnect();
            // 释放CanManager资源，包括关闭ExecutorService
            canManager.release();
        }
        
        serviceListeners.clear();
        notifyServiceListeners();
    }
    
    /**
     * 创建通知渠道
     */
    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(
                    CHANNEL_ID,
                    "CAN通信服务",
                    NotificationManager.IMPORTANCE_LOW
            );
            channel.setDescription("CAN总线数据监控服务");
            channel.setShowBadge(false);
            notificationManager.createNotificationChannel(channel);
        }
    }
    
    /**
     * 启动前台服务
     */
    private void startForegroundService() {
        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(
                this, 0, notificationIntent, 
                Build.VERSION.SDK_INT >= Build.VERSION_CODES.M ? 
                        PendingIntent.FLAG_IMMUTABLE : 0
        );
        
        Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setContentTitle("CAN通信服务运行中")
                .setContentText("正在监控CAN总线数据")
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentIntent(pendingIntent)
                .setOngoing(true)
                .setPriority(NotificationCompat.PRIORITY_LOW)
                .build();
        
        startForeground(NOTIFICATION_ID, notification);
    }
    
    /**
     * 更新通知内容
     */
    private void updateNotification() {
        if (!isServiceRunning) return;
        
        String contentText = String.format("接收: %d 帧, 发送: %d 帧", 
                receivedFrameCount, sentFrameCount);
        
        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(
                this, 0, notificationIntent,
                Build.VERSION.SDK_INT >= Build.VERSION_CODES.M ? 
                        PendingIntent.FLAG_IMMUTABLE : 0
        );
        
        Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setContentTitle("CAN通信服务运行中")
                .setContentText(contentText)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentIntent(pendingIntent)
                .setOngoing(true)
                .setPriority(NotificationCompat.PRIORITY_LOW)
                .build();
        
        notificationManager.notify(NOTIFICATION_ID, notification);
    }
    
    /**
     * 连接CAN总线
     */
    public void connectCan() {
        if (canManager != null) {
            canManager.connect();
        }
    }
    
    /**
     * 断开CAN总线
     */
    public void disconnectCan() {
        if (canManager != null) {
            canManager.disconnect();
        }
    }
    
    /**
     * 发送CAN帧
     */
    public void sendCanFrame(CanFrame frame) {
        if (canManager != null) {
            canManager.sendFrame(frame);
        }
    }
    
    /**
     * 获取CAN连接状态
     */
    public boolean isCanConnected() {
        return canManager != null && canManager.isConnected();
    }
    
    /**
     * 获取服务运行状态
     */
    public boolean isServiceRunning() {
        return isServiceRunning;
    }
    
    /**
     * 获取数据统计
     */
    public int getReceivedFrameCount() {
        return receivedFrameCount;
    }
    
    public int getSentFrameCount() {
        return sentFrameCount;
    }
    
    /**
     * 重置统计数据
     */
    public void resetStatistics() {
        receivedFrameCount = 0;
        sentFrameCount = 0;
        updateNotification();
        notifyDataStatistics();
    }
    
    /**
     * 添加服务监听器
     */
    public void addServiceListener(ServiceListener listener) {
        if (!serviceListeners.contains(listener)) {
            serviceListeners.add(listener);
        }
    }
    
    /**
     * 移除服务监听器
     */
    public void removeServiceListener(ServiceListener listener) {
        serviceListeners.remove(listener);
    }
    
    /**
     * 通知服务状态变化
     */
    private void notifyServiceListeners() {
        for (ServiceListener listener : serviceListeners) {
            listener.onServiceStatusChanged(isServiceRunning);
        }
    }
    
    /**
     * 通知数据统计更新
     */
    private void notifyDataStatistics() {
        for (ServiceListener listener : serviceListeners) {
            listener.onDataStatisticsUpdated(receivedFrameCount, sentFrameCount);
        }
    }
    
    // CanDataListener 接口实现
    @Override
    public void onFrameReceived(CanFrame frame) {
        receivedFrameCount++;
        lastFrameTime = System.currentTimeMillis();
        
        // 每100帧更新一次通知
        if (receivedFrameCount % 100 == 0) {
            updateNotification();
        }
        
        // 每10帧通知一次统计更新
        if (receivedFrameCount % 10 == 0) {
            notifyDataStatistics();
        }
        
        Timber.d("服务接收到CAN帧: %s", frame.toString());
    }
    
    @Override
    public void onFrameSent(CanFrame frame) {
        sentFrameCount++;
        
        // 每50帧更新一次通知
        if (sentFrameCount % 50 == 0) {
            updateNotification();
        }
        
        // 每5帧通知一次统计更新
        if (sentFrameCount % 5 == 0) {
            notifyDataStatistics();
        }
        
        Timber.d("服务发送CAN帧: %s", frame.toString());
    }

    @Override
    public void onJ1939DataReceived(J1939Frame frame) {

    }

    // CanStatusListener 接口实现
    @Override
    public void onConnected() {
        Timber.d("服务: CAN总线已连接");
        updateNotification();
    }
    
    @Override
    public void onDisconnected() {
        Timber.d("服务: CAN总线已断开");
        updateNotification();
    }
    
    @Override
    public void onError(String error) {
        Timber.e("服务: CAN通信错误 - %s", error);
        
        // 更新通知显示错误状态
        if (isServiceRunning) {
            Intent notificationIntent = new Intent(this, MainActivity.class);
            PendingIntent pendingIntent = PendingIntent.getActivity(
                    this, 0, notificationIntent,
                    Build.VERSION.SDK_INT >= Build.VERSION_CODES.M ? 
                            PendingIntent.FLAG_IMMUTABLE : 0
            );
            
            Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
                    .setContentTitle("CAN通信错误")
                    .setContentText(error)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentIntent(pendingIntent)
                    .setOngoing(true)
                    .setPriority(NotificationCompat.PRIORITY_HIGH)
                    .build();
            
            notificationManager.notify(NOTIFICATION_ID, notification);
        }
    }
}